<template>
  <div class="count">
    <div>当前count为：{{ count }}</div>
    <el-select v-model="selectNum" placeholder="请选择" style="width: 120px; margin-right: 16px">
      <el-option
        v-for="item in optionsList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>

    <el-button type="primary" @click="addNum">加</el-button>
    <el-button type="primary" @click="minusNum">减</el-button>
    <el-button type="primary" @click="handleChange">其他方式修改store</el-button>

    <br />
    <br />
    <hr />
    <br />

    <div>从store获取数据： {{ countStore.num }}</div>
    <div>地址为：{{ countStore.address }}, 工作为： {{ countStore.work }}</div>
  </div>
</template>
<script setup lang="ts">
import useCountStore from '@/stores/count.ts'
import { storeToRefs } from 'pinia'

/**
 * 自己组件的count ===> 改成从store中获取
 */
const count = ref(1)
const countStore = useCountStore()
console.log('useCountStore:', countStore)
console.log('useCountStore 的属性:', countStore.num)

console.log('toRefs的store的结构：', toRefs(countStore))
console.log('storeToRefs的store的结构：', storeToRefs(countStore))

const { num: num2, work: work2 } = storeToRefs(countStore)
console.log('解构后的：', num2, work2)

const selectNum = ref(1)
const optionsList = [
  { label: '1', value: 1 },
  { label: '2', value: 2 },
  { label: '3', value: 3 },
]

const addNum = () => {
  count.value = count.value + selectNum.value

  // 1. store直接修改数据
  countStore.num = countStore.num + selectNum.value
  countStore.address += '~'
  countStore.work = '无业有名'
}
const minusNum = () => {
  count.value = count.value - selectNum.value

  // 2. patch方法。且不影响其他没写的字段。
  countStore.$patch({
    work: 'TODO 事情',
    address: '北京',
  })
}
const handleChange = () => {
  // 3. 动作action
  countStore.increment(selectNum.value)
}

countStore.$subscribe((mutation, state) => {
  console.log('监听store的变化：', mutation, state)
})
</script>
<style scoped>
.count {
  border: 1px solid #534b4b;
  padding: 20px;
  background: #bd8a8a;
}
</style>
